package com.heatup.apt.api.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import com.heatup.apt.api.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.heatup.apt.common.util.StringUtil;
import com.heatup.apt.model.user.UserInfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;


/**
 * Base控制器
 * <P>File name : BaseController.java </P>
 * <P>Author : fangxiaowen </P> 
 * <P>Date : 2016年8月24日 </P>
 */
@SuppressWarnings("unchecked")
public class BaseController {

	
	private Logger logger = LoggerFactory.getLogger(BaseController.class);
	@Autowired
	private HttpSession session;
	
	@Autowired
	private UserService userService;
	
	public static final String SESSION_KEY_USERID = "USER_ID";
	public static final String SESSION_KEY_USERINFO = "USER_INFO";
	public static final String SESSION_KEY_MOBILE = "MOBILE";
	public static final String SESSION_KEY_CHECK_CODE = "CHECK_CODE";
	public static final String SESSION_KEY_CHECK_CODE_LAST_SEND = "CHECK_CODE_LAST_SEND";	
	
	protected void setSession(String key, Object value){
		session.setAttribute(key, value);
	}
	
	protected Object getSession(String key){
		return session.getAttribute(key);
	}	
	
	/**
	 * 从session中获取用户id
	 * @return
	 */
	public Integer getUserId(){
		//log.info("session id value is : "+session.getId());
		Object obj = session.getAttribute(SESSION_KEY_USERID);
		//log.info("user is value is : " + obj == null ?  obj + "" : "0000000000000");
		if(obj != null){
			return (Integer)obj;
		}else{
			return null;
		}
	}
	
	protected void setUserId(Integer userId){
		//log.info("session.setUserId userId value is : "+userId);
		session.setAttribute(SESSION_KEY_USERID, userId);
	}
	
	/**
	 * 获取用户信息
	 * @return
	 */
	public UserInfo getUserInfo(){
		Object obj = session.getAttribute(SESSION_KEY_USERINFO);
		//log.info("getUserInfo id value is : "+session.getAttribute(SESSION_KEY_USERINFO));
		if(obj != null){
			logger.info("session userInfo openid value is : "+((UserInfo) obj).getOpenid());
			UserInfo userInfo=  (UserInfo)obj;
				userInfo = userService.getUserInfoById(userInfo.getId());
				logger.info("judge session user level problem "+userInfo.getLevel());
			return userInfo;
		}else{
			return null;
		}		
	}
	
	protected void setUserInfo(UserInfo userInfo){
		//log.info("session set userInfo openid value  is : "+userInfo.getOpenid());
		session.setAttribute(SESSION_KEY_USERINFO, userInfo);
	}	
	
	/**
	 * 判断是否登录
	 * @return
	 */
	public boolean isLogined(){
		return (getUserId()!=null);
	}
	
	/**
	 * 获取参数
	 * BaseController.getParameter()<BR>
	 * <P>Author :  fangxiaowen </P>  
	 * <P>Date : 2016年8月24日 </P>
	 * @param request
	 * @return
	 * @throws Exception
	 */
    protected JSONObject getParameter(HttpServletRequest request) throws Exception {
        request.setCharacterEncoding("UTF-8");
        BufferedReader buff = null;
        StringBuffer str = null;
        str = new StringBuffer();
        String s = null;
        buff = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
        while ((s = buff.readLine()) != null) {
            str.append(s);
        }
        String p = str.toString();
        if (StringUtil.isEmpty(p)) {
            p = "{}";
        }
        JSONObject param = JSONObject.fromObject(p);
        return param;
    }
    
    
    /**
     * 分发数据到页面接收 BaseController.responseSendMsg()<BR>
     * BaseController.responseSendMsg()<BR>
     * <P>Author :  fangxiaowen </P>  
     * <P>Date : 2016年9月19日 </P>
     * @param response
     * @param strMsg
     */
	protected void responseSendMsg(HttpServletResponse response, String strMsg) {
		try {
			response.setContentType("application/json;charset=utf-8");
			response.setCharacterEncoding("utf-8");
			response.getWriter().write(strMsg);
			response.getWriter().flush();
			response.getWriter().close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
